﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using spbtzb;

public partial class Back_BgPicAdd : System.Web.UI.Page
{
    #region Field

    private Boolean session_Logined
    {
        set
        {
            Session["Logined"] = value;
        }
        get
        {
            return Session["Logined"] == null ? false : Convert.ToBoolean(Session["Logined"]);
        }
    }
    #endregion

    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
            if (session_Logined == false)
            {
                Response.Redirect("Login.aspx?ErrorMessage=" + "您未登录，请在此登录");
            }
        }
    }

    private string GetFileNameByPath(string Path)
    {
        return Path.Substring(Path.LastIndexOf("/") + 1, Path.Length - Path.LastIndexOf("/") - 1);
    }

    //上传图像
    protected void UploadButton_Click(object sender, EventArgs e)
    {
        // 上传图片,文件上传目录 
        string path = Server.MapPath("~/imagesUpload/");
        //string imageUrl = "imagesUpload/";
        string newFileName = GetFileNameByPath(img_NewsPic.ImageUrl);
        if (this.fuSampleURL.HasFile) // 是否必须有图样？
        {
            newFileName = UploadPic(path, this.fuSampleURL);
            if (String.IsNullOrEmpty(newFileName))
            {
                Response.Write("<script>alert('图片上传失败，请重新操作或联系管理员!');</script>");
                return;
            }
        }

        //imageUrl += newFileName;
        // insert to the DB
        string strConn = ConString.ConnString;
        string sqlCmd = String.Format("insert into ImageList (ImageURL, Title, LinkURL, Type,IsDisplay) "
                       + "values ('{0}', '{1}', '{2}', '{3}',true )", newFileName,
                       this.tb_Title.Text.Trim(),this.txb_LinkURL.Text, this.ddl_PicType.SelectedValue);
        int iRet = AccessHelper.ExecuteNonQuery(strConn, System.Data.CommandType.Text, sqlCmd);
        if (iRet > 0)
        {
            this.img_NewsPic.ImageUrl = "~/imagesUpload/" + newFileName;
            Response.Write("<script>alert('添加成功。');</script>");
        }
        else
        {
            // 跳转到错误处理页面
            //Response.Redirect("~/Common/ErrorPage.aspx?ErrorMessage=" + "添加图片操作失败，请联系管理员!");                    
            Response.Write("<script>alert('添加失败。');</script>");
        }
    }


    /// <summary>
    /// 上传图片
    /// <param name="path">图片上传目录</param>
    /// <param name="fileUploadControl">文件上传控件</param>
    /// <returns>包装的文件名</returns>
    /// </summary>
    private String UploadPic(String path, System.Web.UI.WebControls.FileUpload fileUploadControl)
    {
        // String path = Server.MapPath("~/UploadImages/");
        if (!System.IO.Directory.Exists(path))
        {
            System.IO.Directory.CreateDirectory(path);
        }

        int iret = -1;
        bool fileOK = false;
        string filepath = "";
        String fileExtension = "";

        String newFileName = "";

        if (fileUploadControl.HasFile)
        {

            fileExtension = System.IO.Path.GetExtension(fileUploadControl.FileName).ToLower();
            String[] allowedExtensions = { ".jpg", ".jpeg", ".png", ".gif", ".bmp" };

            for (int i = 0; i <= allowedExtensions.Length - 1; i++)
            {
                if (fileExtension == allowedExtensions[i])
                {
                    fileOK = true;
                } // 匹配后缀

                if (fileOK)
                {
                    try
                    {
                        newFileName = System.Guid.NewGuid().ToString().ToLower() + fileExtension;
                        filepath = path + newFileName;
                        if(ddl_PicType.SelectedValue == "PPT" | ddl_PicType.SelectedValue == "TPXW")
                            Common.SaveHightQualityThumbnail(fileUploadControl.PostedFile.InputStream, filepath, 229, 189, null);
                        else
                            Common.SaveHightQualityThumbnail(fileUploadControl.PostedFile.InputStream, filepath, 600, 82, null);


                        //filepath = path + fileUploadControl.FileName;
                        //fileUploadControl.PostedFile.SaveAs(filepath);
                        ////上传成功                                            
                        //newFileName = DateTime.Now.ToString("yyyyMMddhhmmss") + fileExtension;
                        //Common.SmallPic(filepath, path + newFileName, 336, 448);//如果出错就会抛出异常    
                        break;
                    }
                    catch (Exception ex)
                    {
                        newFileName = "";
                        //throw new Exception(ex.Message.ToString() + " File could not be uploaded");
                    }
                } // fileOK
            } // 匹配后缀循环结束
        } // 有文件

        return newFileName;
    }// function end

}
